﻿namespace FiftyOne.Foundation.Mobile.Configuration
{
    using System;
    using System.IO;
    using System.Security;

    internal class Support
    {
        private static bool DoesDirectoryOrFileExist(string pathSetOnWebConfig)
        {
            FileInfo info = new FileInfo(pathSetOnWebConfig);
            return (info.Exists || info.Directory.Exists);
        }

        internal static string GetFilePath(string pathSetOnWebConfig)
        {
            if (string.IsNullOrEmpty(pathSetOnWebConfig))
            {
                return string.Empty;
            }
            try
            {
                if (DoesDirectoryOrFileExist(pathSetOnWebConfig))
                {
                    return pathSetOnWebConfig;
                }
            }
            catch (SecurityException)
            {
            }
            if (pathSetOnWebConfig.StartsWith("~"))
            {
                return MakeAbsolute(RemoveTilda(pathSetOnWebConfig));
            }
            return pathSetOnWebConfig;
        }

        internal static string MakeAbsolute(string partialPath)
        {
            if (partialPath.StartsWith(Path.AltDirectorySeparatorChar.ToString()) || partialPath.StartsWith(Path.DirectorySeparatorChar.ToString()))
            {
                partialPath = partialPath.Substring(1, partialPath.Length - 1);
            }
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, partialPath).Replace("/", @"\");
        }

        internal static string RemoveTilda(string partialPath)
        {
            if (partialPath.StartsWith("~"))
            {
                return partialPath.Substring(1, partialPath.Length - 1);
            }
            return partialPath;
        }
    }
}

